package com.ccc.boot.system.service.impl;

import com.ccc.boot.constant.CommonConstant;
import com.ccc.boot.easypoi.util.MyFileUtils;
import com.ccc.boot.exception.BusinessException;
import com.ccc.boot.response.ResponseCode;
import com.ccc.boot.system.entity.SysFile;
import com.ccc.boot.system.mapper.SysFileMapper;
import com.ccc.boot.system.pojo.FileParam;
import com.ccc.boot.system.service.SysFileService;
import com.ccc.boot.system.service.SysUserService;
import com.ccc.boot.util.Base64Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author superC
 * @version 0.1.0
 * @date 2022/4/7
 */
@Service
public class SysFileServiceImpl implements SysFileService {

    protected static final Logger logger = LoggerFactory.getLogger(SysFileServiceImpl.class);

    @Autowired
    private SysFileMapper sysFileMapper;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Long upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException(ResponseCode.UPLOAD_FILE_NULL);
        }

        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        //创建图片存放地址
        File imagePath = MyFileUtils.createFile("/image");
        File imageResultPath = new File(imagePath.getPath() + "/" + fileName);
        if (imageResultPath.exists()) {
            throw new BusinessException(ResponseCode.FILE_IS_EXIST);
        }
        file.transferTo(imageResultPath);

        SysFile sysFile = new SysFile();
        sysFile.setFileName(fileName);
        sysFile.setFilePath(imageResultPath.getPath());
        sysFile.setFileSize(file.getSize());
        sysFile.setFileExt(suffixName);
        sysFile.setFileType(2);
        sysFileMapper.insert(sysFile);

        return sysFile.getId();
    }

    @Override
    public Long upload2DB(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException(ResponseCode.UPLOAD_FILE_NULL);
        }
        InputStream inputStream = file.getInputStream();
        byte[] imageByte = new byte[(int) file.getSize()];
        inputStream.read(imageByte);

        // 文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        SysFile sysFile = new SysFile();
        sysFile.setFileName(fileName);
        sysFile.setFileContent(imageByte);
        sysFile.setFileSize(file.getSize());
        sysFile.setFileExt(suffixName);
        sysFile.setFileType(2);
        sysFileMapper.insert(sysFile);

        return sysFile.getId();
    }


    @Override
    public boolean delete(Long fileId) {
        return sysFileMapper.deleteById(fileId) > 0;
    }

    @Override
    public boolean deleteFile(FileParam fileParam) {
        Long fileId = fileParam.getFileId();
        // 清除业务表相关信息
        if (fileParam.getBusinessId() != null) {
            // 用户个人头像
            if (CommonConstant.BUSINESS_TYPE_USER.equals(fileParam.getBusinessType())) {
                sysUserService.removeImage(fileParam.getBusinessId());
                // 获取当前图片是否关联其他用户
                int count = sysUserService.countUser(fileId);
                if (count > 1) {
                    // 删除图片
                    this.delete(fileId);
                }
                return true;
            }
            // TODO 其他业务

        }
        // 删除图片
        return this.delete(fileId);
    }

    @Override
    public void getFile(Long fileId, HttpServletResponse response) {
        SysFile sysFile = sysFileMapper.selectById(fileId);
        byte[] fileBytes = sysFile.getFileContent();
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = null;
        try {
            outputSream = response.getOutputStream();
            InputStream in = new ByteArrayInputStream(fileBytes);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                outputSream.write(buf, 0, len);
            }
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        } finally {
            try {
                outputSream.close();
            } catch (IOException e) {
                throw new BusinessException(e.getMessage());
            }
        }
    }

    @Override
    public String getFile(Long fileId) {
        return Base64Utils.bytesToBase64(getBytes(fileId));
    }


    @Override
    public String getImage(Long fileId) {
        return Base64Utils.getImageBase64(getBytes(fileId));
    }

    private byte[] getBytes(Long fileId) {
        if (fileId == null) {
            throw new BusinessException(ResponseCode.PARAM_IS_BLANK);
        }
        SysFile sysFile = sysFileMapper.selectById(fileId);
        if (sysFile.getFileContent() == null) {
            logger.error("文件主键ID为{}", fileId);
            throw new BusinessException(ResponseCode.FILE_IS_NOT_EXIST);
        }
        return sysFile.getFileContent();
    }


}